package com.jixiantubu.jinnang;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.example.jixiantubu.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;

import com.jixiantubu.adapter.JinNang_KePu_Adapter;
import com.jixiantubu.bean.Sciencebean;
import com.jixiantubu.util.CustomProgressDialog;
import com.jixiantubu.util.MyApplication;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ViewInject;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class TuiJianFragment extends Fragment {
	@ViewInject(R.id.jinnang_kepu_gv)
	PullToRefreshGridView gridView;
	List<Sciencebean> list = new ArrayList<Sciencebean>();
	JinNang_KePu_Adapter adapter;
	BitmapUtils bitmapUtils;
	MyApplication application;
	View view;
	Context context;
	String url = "http://" + MyApplication.getIP()
			+ ":8080/Jinnang/ScienceService";
	private int number = 1;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.jinnang, null);
		// 取出Activity传过来的数据
		ViewUtils.inject(view);
		context = view.getContext();
		bitmapUtils = new BitmapUtils(getActivity());
		initViews();
		downLoadData(url);
		setgridView();
		onclick();
		return view;
	}

	private void onclick() {
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				//list.get(arg2).getS_id();
				Intent intent = new Intent(getActivity(),
						JinNang_KePu_NeiRongJianJie.class);
				intent.putExtra("id", list.get(arg2));
				context.startActivity(intent);

			}
		});

	}

	private void initViews() {
		gridView = (PullToRefreshGridView) view.findViewById(R.id.jinnang_kepu_gv);		
		adapter = new JinNang_KePu_Adapter(context, list);
		gridView.setAdapter(adapter);
	}

	private void setgridView() {
		// 设置PullToRefreshListView添加上拉和下拉的方式
		gridView.setMode(Mode.BOTH);// 现在是两种都用的情况

		ILoadingLayout freshLayout = gridView
				.getLoadingLayoutProxy(true, false);

		// 修改更新的时间，可以用于提示上次刷新是什么时候
		freshLayout.setLastUpdatedLabel("上次更新2015.10.20");
		// 修改更新的旋转图标
		// freshLayout.setLoadingDrawable(getResources().getDrawable(R.drawable.ic_launcher));
		// 设置下拉的文字
		freshLayout.setPullLabel("下拉刷新");
		// 松开的提示语
		freshLayout.setReleaseLabel("松开刷新");
		// 设置刷新的文字提示
		freshLayout.setRefreshingLabel("正在刷新!请稍等");
		// 设置字体格式
		// freshLayout.setTextTypeface(Typeface.DEFAULT);
		/**
		 * 给PullToRefreshListView添加headView
		 */
		/*HeaderGridView list1 = (HeaderGridView) gridView.getRefreshableView();// 获取PullToRefreshListView中的ListView
		ImageView img = new ImageView(this);
		// img.setImageResource(R.drawable.wo);
		list1.addHeaderView(img);*/

		/**
		 * 为PullToRefreshListView绑定监听器监听用户的下拉和上拉操作
		 */
		gridView.setOnRefreshListener(new OnRefreshListener2<GridView>() {

			@Override
			// 下拉刷新
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
				// 下拉刷新的逻辑代码


				// 1、清空数据集合中的原有的所有的数据
				list.clear();
				// 2、重新请求第一页数据，存入到数据集合中 3、通知UI展示新数据(notifyDataSetChanged)
				downLoadData(url);
				// 4、通知刷新布局，数据加载完成
				gridView.onRefreshComplete();
			}

			protected void addMoreData() {
				// 刷新之后显示下一页内容，当亲为第一页
				number++;// 页数自加；
				if (0 != adapter.getCount() % 5) {
					Toast.makeText(context, "已全部显示",
							Toast.LENGTH_SHORT).show();
				} else {
					String url = "http://" + MyApplication.getIP()
							+ ":8080/Jinnang/ScienceService?key=2&page="
							+ number;
					downLoadData(url);

				}
			}

			@Override
			// 上拉加载
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
	
				addMoreData();
				

				gridView.onRefreshComplete();

			}
		});

	}
	
	
	
	private void downLoadData(String url) {
		final CustomProgressDialog pd = new CustomProgressDialog(
				context, "正在拼命加载数据,请稍等！", R.anim.frame);
		pd.show();
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("key", "2");
		params.addQueryStringParameter("page", "1");
		HttpUtils httpUtils = new HttpUtils();
		MyApplication.httpclient.configSoTimeout(5000);
		httpUtils.send(HttpMethod.POST, url, params,
				new RequestCallBack<String>() {
					@Override
					public void onFailure(HttpException arg0, String arg1) {
						pd.dismiss();
						MyApplication.show(context, "加载数据失败，请检查网络!");
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						// 请求成功
						pd.dismiss();
						ArrayList<Sciencebean> templist;
						String result = arg0.result;
						System.out.println("arg0.result----" + arg0.result);
						Gson gson = new Gson();
						Type type = new TypeToken<List<Sciencebean>>() {
						}.getType();
						templist = gson.fromJson(result, type);
						list.addAll(templist);
						list = gson.fromJson(result, type);
						adapter.setList(list);
						Log.e("胡椒", list.toString());
						adapter.notifyDataSetChanged();
					}
				});
	}




}
